package com.life.wd.Interceptor;

import com.life.wd.utils.JwtUtil;
import com.life.wd.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行预检请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setStatus(403);
            return false;
        }
        try {
            // 验证token
            Map<String, Object> map = JwtUtil.ParseJwt(token);
            ThreadLocalUtil.set(map);
            return true; // 验证通过, 放行
        } catch (Exception e) {
            response.setStatus(403);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":403,\"message\":\"error\",\"data\":登录过期}");
            return false; // 验证失败, 拦截
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();        // 清理ThreadLocal，防止内存泄漏
    }
}
